<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="show" round z-index=104
            custom-style="width: 100%;background:#ffffff;overflow: hidden; ">
            <view class="popup-content">
                <!-- <view class="popup-main"> -->
                <view style="display: flex; justify-content: space-between;">
                    <view class="popupTitle"> 输入核销码</view>
                    <van-icon name="cross" size="15" @click="closePopup" />
                </view>
                <view class="popup-subtitle">输入核销码后开始服务</view>
                <!-- 核销码输入框等内容 -->
                <view class="verification-code-container">
                    <!-- <input type="number" placeholder="请输入核销码" /> -->
                    <!-- 伪装的验证码显示框 -->
                    <view class="code-boxs" @click="focusInput">
                        <block v-for="(item, index) in 6" :key="index">
                            <view class="code-box" :class="{ active: currentIndex === index }">
                                {{ codeArr[index] || '' }}
                                <!-- 光标动画 -->
                                <view class="cursor" v-if="currentIndex === index && isFocus"
                                    :animation="cursorAnimation"></view>
                            </view>
                        </block>
                    </view>

                    <!-- 隐藏的真实输入框 -->
                    <input id="realInput" type="number" maxlength="6" :focus="isFocus" :value="code" @input="onInput"
                        @focus="onFocus" @blur="onBlur" style="width:0;height:0;position:absolute;left:-999rpx;" />
                </view>
                <view class="errorTips" v-if="error">当前核销码输入错误，请核查！</view>
                <van-button type="primary" @tap="startService" :disabled="isSubmitting"
                :class="{ 'disabled-btn': isSubmitting }">开始服务</van-button>
            </view>
        </van-popup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import {startServiceApi,queryServiceByCodeApi} from '@/api/staff'
export default {
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        popupParams: {
            type: Object,
            default: () => ({})
        },
        reservationId: {
            type: String,
            default: ''
        }
    },
    data () {
        return {
            curS:0,
            curSName:'',
            date: '',
            title: '取消订单',
            option: {},
            url: '',
            popupHeight:'500',
            error:false,
            code: '',          // 输入的验证码
            codeArr: [],       // 拆分成数组的验证码
            isFocus: false,    // 是否聚焦
            currentIndex: 0,   // 当前聚焦位置
            cursorAnimation: null, // 光标动画
            isSubmitting: false, // 新增防抖状态
            isAnimationInitialized: false // 新增动画初始化状态标识
        }
    },

    computed: {
    },


    watch:{
        show : {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    // Clear input fields when popup is shown
                    this.code = '';
                    this.codeArr = [];
                    this.currentIndex = 0;
                    this.error = false;
                    this.isAnimationInitialized = false;
                }
            }
        }
    },
    onLoad () { 
        this.initCursorAnimation()
    },
    onReady () {},

    methods: {
       
        // 关闭弹窗
        closePopup () {
            this.isCancel=false
            this.$emit('closeEnterlPopup',this.isCancel)
        },

        // 开始服务
        async startService() {
            if (this.isSubmitting) return;
            this.isSubmitting = true;

            await this.startServiceMethod();
            if (!this.error) {
                this.closePopup();
                this.$emit('startService');
            }
            setTimeout(() => {
                this.isSubmitting = false;
            }, 1000);
        },

        async startServiceMethod() {
            try {
                const res = await startServiceApi(this.popupParams);
                if (res.code == 200) {
                    this.error = false;
                    this.curS = res.data.id;
                    this.curSName = res.data.name;
                    return true; // 返回成功状态
                } else {
                    this.error = true;
                    setTimeout(() => {
                        this.closePopup();
                    }, 5000);
                    return false;
                }
            } catch (e) {
                // this.error = true;
                setTimeout(() => {
                    this.closePopup();
                }, 5000);
                return false;
            }
        },
         // 初始化光标动画
         initCursorAnimation() {
             try {
                if (typeof wx !== 'undefined' && wx.createAnimation) {
                 const animation = wx.createAnimation({
                     duration: 800,
                     timingFunction: 'step-start'
                 })
                 this.animation = animation
                 this.isAnimationInitialized = true;
                 this.playCursorAnimation()
                }else{
                    console.log('wx.createAnimation is not available.');
                }
             } catch (error) {
                 console.error('Error initializing cursor animation:', error);
             }
        },

        // 播放光标闪烁动画
        playCursorAnimation() {
            if (!this.isAnimationInitialized) {
                this.initCursorAnimation();
                return;
            }
            if (!this.animation) {
                console.error('Animation object is not initialized.');
                return;
            }
            this.animation.opacity(0).step()
            this.animation.opacity(1).step()
            this.cursorAnimation = this.animation.export()
            this.cursorTimer = setTimeout(() => {
            this.playCursorAnimation()
            }, 800)
        },

        // 点击输入区域
        focusInput() {
            this.isFocus = true
        },

        // 输入事件处理
        onInput(e) {
            console.log(e,e.detail.value)
            const value = e.detail.value
            const newCode = value.replace(/[^0-9]/g, '') // 只保留数字
            const codeArr = newCode.split('')
            
            this.code = newCode
            this.codeArr = codeArr
            this.currentIndex = Math.min(newCode.length, 5)

            // 输入完成回调
            if (newCode.length === 6) {
            // wx.showToast({ title: '输入完成' })
            // 这里可以触发验证码提交逻辑
            // this.verifyCode(newCode)
            }
            if (this.code.length === 6) {
                this.isSubmitting = false
                queryServiceByCodeApi({ code: this.code,reservationId:this.reservationId }).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                      this.error = false
                      this.isSubmitting = false
                    }else{
                      this.error = true
                      this.isSubmitting = true
                    }
                })
            }else{
                this.isSubmitting = true
                return false
            }
        },

        // 聚焦事件
        onFocus() {
            clearTimeout(this.cursorTimer)
            this.playCursorAnimation()
            this.isFocus = true
        },

        // 失焦事件
        onBlur() {
            clearTimeout(this.cursorTimer)
            this.isFocus = false
        },

        onUnload() {
            clearTimeout(this.cursorTimer)
        },
        // 验证验证码

        // 根据code查询
        // async queryServiceByCode(){
        //     try {
        //         const res = await queryServiceByCodeApi({ code: this.code })
        //         console.log(res)
        //         if (res.code == 200) {
        //             this.error = false
        //             this.curS = res.data.id
        //             this.curSName = res.data.name
        //         } else {
        //             this.error = true
        //         }
        //     } finally{
        //         this.isSubmitting = false
        //     }
        // }

  },

}
</script>
<style lang="scss" scoped>

// 提示框
.popup-content {
    padding: 24px;
    font-size: 12px;
    background: #ffffff;
    border-radius: 16px;
    overflow: hidden;
    height: 50%;

    .popupTitle {
        font-size: 20px;
        text-align: left;
        color: #111111;
        line-height: 20px;
    }
}
.popup-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
//   box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.popup-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.popup-subtitle {
  font-size: 14px;
  color: #999;
  margin-bottom: 16px;
  margin-top: 32rpx;
}
.verification-code-container {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}
.verification-code-container input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.errorTips{
    margin-top: 16rpx;
    margin-bottom: 24rpx;
    font-weight: 400;
    font-size: 24rpx;
    text-align: left;
    color: #f00000;
}

// 输入框
.code-boxs {
  display: flex;
  gap: 20rpx;
}

.code-box {
  width: 80rpx;
  height: 100rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 44rpx;
  position: relative;
}

.code-box.active {
  border-color: #07c160;
}

.cursor {
  width: 2rpx;
  height: 50rpx;
  background: #333;
  position: absolute;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
.disabled-btn {
    // background-color: #cccccc !important;
    border-color: #cccccc !important;
}
</style>

